'use strict';

const Service = require('egg').Service;

class ZanService extends Service {
  constructor(ctx) {
    super(ctx);
    this.user = {};
  }

  async create(params) {
    const { mysql } = this.app;
    try {
      const {
        type,
        type_id,
      } = params;
      const user_id = this.ctx.user.user_id;
      const status = 1;
      const created_at = new Date();
      const updated_at = new Date();
      const result = await mysql.query(`INSERT INTO cms_zan(type, type_id, user_id, status, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?)`,
      [ type, type_id, user_id, status, created_at, updated_at ]);

      if (result.affectedRows === 1) {
        return result.insertId;
      }
      throw new Error(result.message);
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }

  async destroy(params) {
    const { mysql } = this.app;
    try {
      const {
        id,
      } = params;
      const status = 0;
      const user_id = this.ctx.user.user_id;
      const updated_at = new Date();
      const result = await mysql.query('UPDATE `cms_zan` SET `status`=?, `user_id`=?, `updated_at`=? WHERE `id`=?', [ status, user_id, updated_at, id ]);

      if (result.affectedRows === 1) {
        return result.insertId;
      }
      throw new Error(result.message);
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }
}

module.exports = ZanService;
